package apis

import (
	"appshop/app/admin/service"
	"appshop/app/admin/service/dto"
	result "appshop/commons/error"
	"appshop/commons/utils"
	"appshop/conf"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"mime/multipart"
	"net/http"
	"path"
	"strconv"
)

// LoadAppRouter 路由管理
func LoadAppRouter(e *gin.Engine) {
	// 限制文件上传时使用的内存大小，默认为32M
	e.MaxMultipartMemory = 8 << 20 // 8M

	e.GET("/app/:id", getApp)
	e.GET("/app/list", getAppList)
	e.POST("/app", addApp)
}

func getApp(c *gin.Context) {
	utils.Info("查询应用信息", c.Params)
	// fmt.Println("查询应用信息")
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, result.ErrParam)
		return
	}
	// fmt.Println("参数 id = ", id)
	utils.Info("参数 id = ", id)
	appDetails, err := service.GetById(int64(id))
	if err != nil {
		utils.Danger("查询应用信息异常,", err)
		c.JSON(http.StatusInternalServerError, result.Fail.WithMsg(err.Error()))
		return
	}
	c.JSON(http.StatusOK, result.OK.WithData(appDetails))
}

func getAppList(c *gin.Context) {
	// fmt.Println("查询应用信息列表")
	utils.Info("查询应用信息列表", c.Params)
	var appSearch dto.AppSearch
	packageName := c.Query("packageName")
	// if packageName == "" {
	// 	c.JSON(http.StatusBadRequest, result.ErrParam)
	// 	return
	// }
	appSearch.PackageName = packageName

	var apps []dto.AppCollection
	apps, err := service.GetAppMenu(appSearch)
	if err != nil {
		utils.Danger("查询应用信息列表异常,", err)
		c.JSON(http.StatusInternalServerError, result.Fail.WithMsg(err.Error()))
		return
	}
	c.JSON(http.StatusOK, result.OK.WithData(apps))
}

func addApp(c *gin.Context) {
	// fmt.Println("新增应用信息")
	utils.Info("新增应用信息", c.Params)
	var form dto.AppReq

	err2 := c.Bind(&form)
	// 解析并绑定form数据
	if err2 != nil {
		utils.Danger("新增应用信息异常,", err2)
		c.JSON(http.StatusBadRequest, result.ErrParam)
		return
	}

	// 初始化参数
	app := form.Generate()
	// app.PackageAddTime = time.Now().Unix()

	file, err := c.FormFile("packageFile")
	if err != nil {
		utils.Danger("新增应用信息异常,", err)
		c.JSON(http.StatusBadRequest, result.ErrFileUpload)
		return
	}
	icon, err := c.FormFile("packageIcon")
	if err != nil {
		utils.Danger("新增应用信息异常,", err)
		c.JSON(http.StatusBadRequest, result.ErrFileUpload)
		return
	}

	// 业务逻辑
	// 调用service 保存到数据库
	exists, err := service.CheckExists(app.PackageBundleId, app.PackageVersion)
	if err != nil {
		utils.Danger("校验应用信息异常,", err)
		c.JSON(http.StatusInternalServerError, result.Fail.WithMsg(err.Error()))
		return
	}
	if exists {
		utils.Info("已存在相同的应用包,", app)
		c.JSON(http.StatusOK, result.OK.WithMsg("已存在相同的应用包"))
		return
	}

	// 保存文件
	filePath, err := saveFile(c, file)
	if err != nil {
		utils.Danger("保存文件异常,", err)
		c.JSON(http.StatusInternalServerError, result.Fail)
		return
	}
	// 保存icon
	iconPath, err := saveFile(c, icon)
	if err != nil {
		utils.Danger("保存文件异常,", err)
		c.JSON(http.StatusInternalServerError, result.Fail)
		return
	}
	app.PackagePath = filePath
	app.PackageIcon = iconPath
	res, err := service.Insert(app)
	if err != nil {
		utils.Danger("新增应用信息异常,", err)
		c.JSON(http.StatusInternalServerError, result.Fail.WithMsg(err.Error()))
		return
	}
	c.JSON(http.StatusOK, result.OK.WithData(res))

}

func saveFile(c *gin.Context, file *multipart.FileHeader) (string, error) {
	var filePath string

	// 保存路径为 /root/work/GO/temp/app/[filename] ,存储路径为/upload/[filename]
	uuid := uuid.NewString()
	filePath = conf.Config.File.UploadPath + uuid + "_" + file.Filename

	// 可替换为不同的文件保存方法，
	err := c.SaveUploadedFile(file, filePath)
	if err != nil {
		// fmt.Println("文件保存失败,", filePath)
		utils.Danger("文件保存失败,", filePath)
		return "", err
	}

	// fmt.Println("文件保存成功,", path.Clean(filePath))
	utils.Info("文件保存成功,", path.Clean(filePath))
	return "/upload/" + uuid + "_" + file.Filename, nil
}
